package com.qk.Dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.qk.my.pojos.Answer;
import com.qk.my.pojos.Player;
import com.qk.my.pojos.Question;

public class QuestionDao {
	private static SqlSession session;
	private static String statement;
	static {
		session = SqlSessionDao.getSession();
	}

	public static List<Question> getAllQuestion() {
		statement = "com.qk.mapping.Questionmapper.getAllQuestion";
		List<Question> answer = session.selectList(statement);
		return answer;

	}

	public static List<Question> searchQuestionMINE(int id) {
		statement = "com.qk.mapping.Questionmapper.searchQuestionMINE";
		List<Question> answer = session.selectList(statement, id);
		return answer;

	}

	public static List<Question> searchQuestionOpen() {
		statement = "com.qk.mapping.Questionmapper.searchQuestionOpen";
		List<Question> answer = session.selectList(statement);
		return answer;

	}

	public static Question getQuestionById(int id) {
		statement = "com.qk.mapping.Questionmapper.getQuestionById";
		Question answer = session.selectOne(statement, id);
		return answer;
	}

	public static int insertQuestion(Question question) {
		statement = "com.qk.mapping.Questionmapper.insertQuestion";
		int i = session.insert(statement, question);
		session.commit();
		return i;
	}

	public static int updateQuestion(Question question) {
		statement = "com.qk.mapping.Questionmapper.updateQuestion";
		int i = session.update(statement, question);

		session.commit();
		return i;
	}

	public static boolean acceptAnswer(Question question, Answer answer) {
		question.setIsOpen("n");
		answer.setBest("y");
		Player player = answer.getPlayer();
		player.setScore(player.getScore() + question.getCredit());
		if (updateQuestion(question) != 1)
			return false;
		if (PlayerDao.updatePlayer(player) != 1)
			return false;
		if (AnswerDao.updateAnswer(answer) != 1)
			return false;
		return true;

	}

}
